package edu.nf.exam.controller;

import com.github.pagehelper.PageInfo;
import edu.nf.exam.entity.UserInfo;
import edu.nf.exam.exception.LoginException;
import edu.nf.exam.service.UserService;
import edu.nf.exam.service.impl.UserServiceImpl;
import edu.nf.exam.vo.ResultVO;
import org.nf.mvc.annotation.RequestMapping;
import org.nf.mvc.servlet.View;
import org.nf.mvc.view.JsonView;

import java.util.List;


/**
 * @Author : PYY
 * @create 2021/6/17
 */
public class UserController extends BaseController{
    /**
     * 根据用户名查询用户信息
     * @param user
     * @return
     */
    @RequestMapping("/user/login")
    public View login(UserInfo user){
        //创建业务逻辑
        UserService service = new UserServiceImpl();
        try {
            UserInfo u = service.checkUser(user);

            JsonView jsonView = new JsonView(success(u));
            jsonView.setDateFormat("yyyy-MM-dd");
            return jsonView;
        }catch (LoginException e){
            e.printStackTrace();
            //响应错误内容的vo
            ResultVO failVo = fail(401, e.getMessage());
            return new JsonView(failVo);
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("/user/reg")
    public View register(UserInfo user){
        //创建业务逻辑
        UserService service = new UserServiceImpl();
       try {

           int r = service.checkRegister(user);

           //返回成功的ResultVO
           return new JsonView(success());

       }catch (LoginException e){
           e.printStackTrace();
           //响应错误内容的vo
           ResultVO resultVO = fail(401, e.getMessage());
           return  new JsonView(resultVO);
       }

    }

    /**
     * 多条件查询用户
     * @param userInfo
     * @return
     */
    @RequestMapping("/user/select")
    public View select(UserInfo userInfo){
        List<UserInfo> list = new UserServiceImpl().select(userInfo);
        return new JsonView(success(list));
    }

    /**
     * 用户修改信息
     * @param userInfo
     * @return
     */
    @RequestMapping("/user/update")
    public View update(UserInfo userInfo){
        UserService userService = new UserServiceImpl();
        try {
            userService.checkUpdate(userInfo);

            return new JsonView(success("更新成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonView(fail(500,e.getMessage()));
        }

    }


    /**
     * 分页查询
     * @param userName
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/user/listUser")
    public View listStudent(Integer userId,String userName,Integer role, Integer page, Integer limit) {
        UserService service = new UserServiceImpl();
        PageInfo<UserInfo> pageInfo = service.listUserInfo(userId, userName, role, page, limit);

        JsonView jsonView = new JsonView(page(pageInfo));
        jsonView.setDateFormat("yyyy-MM-dd");
        return jsonView;

    }

}
